# -*- encoding: utf-8 -*-

"""
@File:      tc_readline_fun_004.py
@Time:      2024-03-01 16:40:00
@Author:    qintingting
@Version:   1.0
@Contact:   wb-qtt862918@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    qintingting
"""
from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_readline_fun_004.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "readline readline-devel"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline='''cat > readline_fun_004.c <<EOF
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>

int main() {
    // 使用 using_history() 初始化历史记录功能
    using_history();

    // 添加几个条目到历史记录
    add_history("ls -la");
    add_history("grep 'something' file.txt");
    add_history("pwd");

    // 打印当前的历史记录
    printf("History list before clearing:\\n");
    HIST_ENTRY **the_history = history_list();
    if (the_history) {
        for (int i = 0; the_history[i]; ++i) {
            printf(" %d: %s\\n", i + 1, the_history[i]->line);
        }
    }

    // 清除历史记录
    clear_history();

    printf("\\nHistory list after clearing:\\n");
    the_history = history_list();
    if (the_history && the_history[0] == NULL) { // 如果 the_history[0] 为 NULL，则历史记录已清空
        printf("History cleared successfully.\\n");
    } else {
        printf("Error: History not cleared!\\n");
        return 1;
    }

    return 0;
}
EOF
'''
        self.cmd(cmdline)

    def test(self):
        self.cmd("gcc -o readline_fun_004 readline_fun_004.c -lhistory -lreadline")
        code, result = self.cmd("file readline_fun_004")
        self.assertIn("executable", result)
        code, result = self.cmd("./readline_fun_004")
        #Confirm that the command is correctly added to the history list
        self.assertIn("ls -la", result)
        self.assertIn("grep 'something' file.txt", result)
        self.assertIn("pwd", result)
        #check successful cleaning history
        self.assertIn("History cleared successfully", result)
         
    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf readline_fun_004 readline_fun_004.c")